package com.example.administrator.energyida.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.example.administrator.energyida.R;
import com.example.administrator.energyida.beans.CompanyBean;
import com.example.administrator.energyida.beans.FactoryBean;
import com.example.administrator.energyida.util.OceanUtil;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Random;

public class HomeMapActivity extends Activity implements View.OnClickListener{

    private MapView mMapView;
    private AMap aMap;
    private TextView text_map_back;

    private String email;
    private Handler handler;
    private String responseFactory;
    private String responseCompany;

    private List<FactoryBean.ContentBean> listFactoryBeans;
    private List<CompanyBean.ContentBean> listCompanyBeans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);//设置对应的XML布局文件

        // 设置状态栏的颜色
        StatusBarUtil.setColor(this, Color.parseColor("#10cafd"), 50);

        initViews();
        initHandler();

        text_map_back.setOnClickListener(this);


        mMapView.onCreate(savedInstanceState);// 此方法必须重写

        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {

            }
        });
    }

    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        if (responseCompany.contains("10007")) {
                            Log.i("坐标", "获得公司信息成功 ");
                            Gson gson = new Gson();
                            CompanyBean companyBean = gson.fromJson(responseCompany, CompanyBean.class);
                            listCompanyBeans = companyBean.getContent();

                            String companyName = listCompanyBeans.get(0).getCompany();
                            double latitude = listCompanyBeans.get(0).getLatitude();
                            double longitude = listCompanyBeans.get(0).getLongitude();

                            LatLng latLngCenter = new LatLng(latitude, longitude);//构造一个位置
                            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter, 17));

                            LatLng latLngCompany = new LatLng(latitude, longitude);
                            final Marker marker = aMap.addMarker(new MarkerOptions().position(latLngCompany).title(companyName));
                            marker.showInfoWindow();
                        }
                        if (responseFactory.contains("-20007")) {
                            Toast.makeText(HomeMapActivity.this, "公司信息获取失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 1:
                        if (responseFactory.contains("10007")) {
                            Log.i("坐标", "获得公司信息成功 ");
                            Gson gson = new Gson();
                            FactoryBean factoryBean = gson.fromJson(responseFactory, FactoryBean.class);
                            listFactoryBeans = factoryBean.getContent();

                            for (int i = 0; i < listFactoryBeans.size(); i++) {
                                String factoryName = listFactoryBeans.get(i).getFName();
                                double fLatitude = listFactoryBeans.get(i).getFLatitude();
                                double fLongitude = listFactoryBeans.get(i).getFLongitude();

                                String detail = "";
                                Random random = new Random();
                                String fUseWater = listFactoryBeans.get(i).getFWater();
                                if (fUseWater.equals("1")) {
                                    int r = random.nextInt(50);
                                    detail += "水：" + r + "\n";
                                }
                                String fElectricity = listFactoryBeans.get(i).getFElectricity();
                                if (fElectricity.equals("1")) {
                                    int r = random.nextInt(50);
                                    detail += "电：" + r + "\n";
                                }
                                String fGas = listFactoryBeans.get(i).getFGas();
                                if (fGas.equals("1")) {
                                    int r = random.nextInt(50);
                                    detail += "气：" + r + "\n";
                                }
                                String fHeat = listFactoryBeans.get(i).getFHeat();
                                if (fHeat.equals("1")) {
                                    int r = random.nextInt(50);
                                    detail += "热：" + r + "";
                                }

                                LatLng latLngFactory = new LatLng(fLatitude, fLongitude);

                                final Marker marker = aMap.addMarker(new MarkerOptions().position(latLngFactory).icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                        .decodeResource(getResources(),R.drawable.ic_location))).title(factoryName).snippet(detail));
                                marker.showInfoWindow();
                            }

                        }
                        if (responseFactory.contains("-20007")) {
                            Toast.makeText(HomeMapActivity.this, "公司信息获取失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }
        };
    }

    private void initViews() {
        text_map_back = findViewById(R.id.text_map_back);
        mMapView = findViewById(R.id.home_map);

        SharedPreferences sharedPreferences = getSharedPreferences("account", MODE_PRIVATE);
        email = sharedPreferences.getString("email", "");

        JSONObject getFactoryPoint = new JSONObject();
        try {
            getFactoryPoint.put("email", email);
            getFactoryPoint.put("mode", 2);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new OceanUtil("getAccountAllInfo.php", getFactoryPoint, new OceanUtil.HttpRequestCallback() {
            @Override
            public void callback(String strResponse) {
                responseFactory = strResponse;
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        }).postInfo();

        JSONObject getCompanyPoint = new JSONObject();
        try {
            getCompanyPoint.put("email", email);
            getCompanyPoint.put("mode", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new OceanUtil("getAccountAllInfo.php", getCompanyPoint, new OceanUtil.HttpRequestCallback() {
            @Override
            public void callback(String strResponse) {
                responseCompany = strResponse;
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
            }
        }).postInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_map_back:
                finish();
                break;
            default:
                break;
        }
    }
}
